package com.hs.srm.admin.modules.orders.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hs.srm.admin.modules.orders.entity.ScmPoChangeEntity;
import com.hs.srm.admin.modules.orders.entity.ScmPoHeaderEntity;
import com.hs.srm.admin.modules.orders.entity.ScmPoItemEntity;
import com.hs.srm.admin.modules.orders.service.ScmPoChangeService;
import com.hs.srm.admin.modules.orders.service.ScmPoHeaderService;
import com.hs.srm.admin.modules.orders.service.ScmPoItemService;
import com.hs.srm.admin.modules.orders.vo.ScmPoItemVo;
import com.hs.srm.admin.modules.sys.controller.AbstractController;
import com.hs.srm.admin.modules.vendor.entity.VendorInfoEntity;
import com.hs.srm.admin.modules.vendor.service.VendorService;
import com.hs.srm.base.common.annotation.SysLog;
import com.hs.srm.base.common.utils.EntityUtils;
import com.hs.srm.base.modules.sys.entity.SysUserEntity;
import com.hs.srm.common.utils.PageUtils;
import com.hs.srm.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import sunnykid.Sunnykid;
import sunnykid.lang.LangException;
import sunnykid.lang.SunnykidDate;
import sunnykid.text.SunnykidText;

import java.math.BigDecimal;
import java.util.*;

/**
 * 采购订单头信息控制层
 * 
 * @author Sunnykid
 *
 * @date 2019年3月17日
 */
@Controller
@RequestMapping("/orderHead")
public class ScmPoHeaderController extends AbstractController {

	private static final long serialVersionUID = -4043915412741090283L;

	@Autowired
	private ScmPoHeaderService scmPoHeaderService;

	@Autowired
	private ScmPoItemService scmPoItemService;

	@Autowired
	private VendorService vendorService;

	@Autowired
	private ScmPoChangeService scmPoChangeService;

	
	/**
	 * 查询订单列表
	 */
	@RequestMapping("/list")
	@ResponseBody
	public R list(@RequestParam Map<String, Object> params) {
		SysUserEntity username = this.getUser();
		if(username.getDeptId()==13){
			params.put("username",username.getUsername());
		}
		PageUtils pu = this.scmPoHeaderService.selectDetailPage(params);
		List<ScmPoItemVo> voList = (List<ScmPoItemVo>)pu.getList();
		voList = EntityUtils.valToTxt(voList);
		pu.setList(voList);
		return R.ok(pu);
	}
	
	/**   
	 * 跳转至订单更改页面
	 * @param poNo
	 * @return
	 */
	@RequestMapping("/toEdit/{poNo}")
	public ModelAndView toEdit(@PathVariable("poNo") String poNo) {
		ScmPoHeaderEntity header = this.scmPoHeaderService.getByPoNo(poNo);
		List<ScmPoItemEntity> items = this.scmPoItemService.getByPoNo(poNo);
		ModelAndView modelAndView = new ModelAndView("modules/orders/npro_orders_edit");
		modelAndView.addObject("header", header);
		modelAndView.addObject("items", items);
		return modelAndView;
	}

	/**
	 * 根据stock收货记录查询相应的订单头信息
	 */
	@RequestMapping("/getByStock")
	@ResponseBody
	public R getByStock(@RequestParam Map<String, Object> params) {
		SysUserEntity username = this.getUser();
		if (username.getDeptId() == 13) {
			params.put("username", username.getUsername());
		}
		PageUtils pu = this.scmPoHeaderService.findByStock(params);
		return R.ok(pu);
	}

	/**   
	 * 更改订单的信息
	 * @param data
	 * @return
	 */
	@SuppressWarnings("boxing")
	@SysLog("更改订单的信息")
	@RequestMapping(value = "/edit", produces = "application/json; utf-8")
	@ResponseBody
	@Transactional
	public R edit(@RequestBody JSONObject data) {
		boolean headerChange = false;
		Map<String, Integer> itemsChange = new HashMap<String, Integer>();
		String poId = (String)data.get("poId");
		String vendorCode = (String)data.get("vendorId");
		ScmPoHeaderEntity header = this.scmPoHeaderService.selectById(poId);

		ScmPoChangeEntity scmPoChange = new ScmPoChangeEntity();
		scmPoChange.setApprNo(SunnykidText.getUUID());

		if(!Sunnykid.assertEqual(header.getVendorId(), vendorCode)) {
			scmPoChange.setVendor1(header.getVendorId());
			scmPoChange.setVendor2(vendorCode);
			headerChange = true;
		}

		VendorInfoEntity vendor=vendorService.selectByVendorCode(vendorCode);
		JSONArray jsonArr = data.getJSONArray("items");
		//行项目的id
		String poItemId =null;
		//价格
		BigDecimal poPrice = null;
		//数量
		BigDecimal poCount = null;
		//交期
		Date deliveryDate= null;
		for(Iterator<?> iterator = jsonArr.iterator(); iterator.hasNext();) {
			JSONObject itemObj = (JSONObject)iterator.next();
			poItemId = (String)itemObj.get("poItemId");
			poPrice = new BigDecimal(itemObj.get("poPrice").toString());
			poCount = new BigDecimal(itemObj.get("poCount").toString());
			try {
				deliveryDate = SunnykidDate.parseSunnykidDate(itemObj.get("deliveryDate").toString());
			} catch(LangException ex) {
				throw new RuntimeException("交期日期处理出错：" + itemObj.get("deliveryDate").toString(), ex);
			}

			ScmPoItemEntity item = this.scmPoItemService.selectById(poItemId);
			Set<String> itemChange = new HashSet<String>();

			if(!Sunnykid.assertEqual(item.getPoCount(), poCount)) {
				scmPoChange.setAmount1(item.getPoCount());
				scmPoChange.setAmount2(poCount);
				itemChange.add("PoCount");
			}
			if(!Sunnykid.assertEqual(item.getPoPrice(), poPrice)) {
				scmPoChange.setPrice1(item.getPoPrice());
				scmPoChange.setPrice2(poPrice);
				itemChange.add("poPrice");
			}
			if(!Sunnykid.assertEqual(item.getDeliveryDate(), deliveryDate)) {
				scmPoChange.setApplyDate1(item.getDeliveryDate());
				scmPoChange.setApplyDate2(deliveryDate);
				itemChange.add("deliveryDate");
			}
			itemsChange.put(poItemId, itemChange.size());
		}
		if(headerChange || !itemsChange.isEmpty()) {
			header.setApprNo(scmPoChange.getApprNo());
			header.setApprStatus(ScmPoHeaderEntity.SHEN_PI_ZHONG);
			scmPoChange.setDealDate(new Date());
			scmPoChange.setDealPerson(this.getUser().getUsername());
			scmPoChange.setApprovalStatus(ScmPoChangeEntity.SHEN_PI_ZHONG);
			this.scmPoChangeService.insert(scmPoChange);
			//更新供应商id
			ScmPoHeaderEntity headerEntity=new ScmPoHeaderEntity();
			headerEntity.setPoId(poId);
			headerEntity.setVendorId(vendorCode);
			headerEntity.setCompanyName(vendor.getVendorName());
			scmPoHeaderService.updateVendorById(headerEntity);
			//更新item 价格、数量、交期等变更内容
			ScmPoItemEntity itemEntity=new ScmPoItemEntity();
			itemEntity.setPoItemId(poItemId);
			itemEntity.setPoPrice(poPrice);
			itemEntity.setPoCount(poCount);
			itemEntity.setDeliveryDate(deliveryDate);
			scmPoItemService.updateOrderInfoById(itemEntity);
		}
		int changeFix = (headerChange ? 1 : 0);
		for(Integer i : itemsChange.values()) {
			changeFix += i.intValue();
		}
		return R.ok(changeFix);
	}

}
